package com.kong.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kong.constant.MessageConstant;
import com.kong.constant.RedisConstant;
import com.kong.entity.Result;
import com.kong.pojo.Member;
import com.kong.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author yang2013
 * @data 2020/10/15 20:20
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;
    /**
     * 登陆--登陆之后保存密码
     * @param map
     * @param response
     * @return
     */
    @RequestMapping("/check")
    public Result loginCheck(@RequestBody Map<String, Object> map, HttpServletResponse response){
        try {
            //{telephone: "13311122211", validateCode: "11111"}
            //1.用户输入的验证码和redis的验证码校验
            Jedis jedis = jedisPool.getResource();
            String telephone = map.get("telephone").toString();
            String validateCode = map.get("validateCode").toString();
            String key= RedisConstant.SENDTYPE_ORDER+"_"+telephone;

            String value = jedis.get(key);
            if (StringUtils.isEmpty(validateCode)){
                return new Result(false, MessageConstant.VALIDATECODE_FAIL);
            }
            //判断验证码
            if (!validateCode.equals(value)){
                return new Result(false,MessageConstant.VALIDATECODE_ERROR);
            }

            //通过号码查询用户的信息
            Member member=memberService.findByPhone(telephone);
            //不存在直接注册
            if (member==null){
                Member member1=new Member();
                member.setPhoneNumber(telephone);
                memberService.add(member1);
            }
            //封装cooike
            Cookie cookie=new Cookie("login_member_telephone",telephone);
            //任意网站都可以获取值
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*365);
            //将cookie封装到response中进行返回
            response.addCookie(cookie);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.LOGIN_FAIL);
        }
    }
}
